package gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Rectangle;
import java.awt.SystemColor;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.border.BevelBorder;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableCellRenderer;

import person.DayPlan;
import person.Interval;
import person.Person;
import person.PersonAchive;
import person.Sex;
import personInfo.PersonTableModel;
import sensor.Sensor;
import sensor.SensorType;
import constants.Constants;

public class FamilyDialog extends JDialog {

	private static final long serialVersionUID = 1L;

	public static void main(String args[]) {
		new FamilyDialog(new JFrame()).setVisible(true);
	}

	JButton Add = null;
	private JButton AddMember = null;
	JDialog AddMemberDialog = null; // @jve:decl-index=0:visual-constraint="444,23"
	private JButton AddRFSensor = null;
	private JTextField AgeField = null;
	private JLabel aLabel = null;
	private JButton Cancel = null;
	private JLabel ErrorLabel = null;
	private JTextField firstName = null;
	private JLabel fnLabel = null;
	private JLabel FormatInfo = null;
	private JPanel jContentPane = null;
	private JTextField lastName = null;
	private JLabel lnLabel = null;
	private JPanel memberDialogPanel = null;
	private JPanel MemberInfo = null;
	public JList MemberList = null;
	JPanel MemberSchedule = null;
	/**
	 * This method initializes AddRFSensor
	 * 
	 * @return javax.swing.JButton
	 */

	Sensor rfid;
	private JLabel rfLabel = null;
	private JLabel Schedule = null;
	JCheckBox scheduleCB = null;

	JTable ScheduleTable = null;

	private int selected = 0;

	private JComboBox sex = null;

	private JLabel sLabel = null;

	private JScrollPane TableScrollPanel; // @jve:decl-index=0:

	/**
	 * @param owner
	 */
	public FamilyDialog(Frame owner) {
		super(owner);
		initialize();
	}

	private DayPlan buildDayPlan() {
		System.out.println("building plan");
		DayPlan dp = new DayPlan();
		boolean returnVal = false;
		for (int i = 0; i < ScheduleTable.getModel().getRowCount(); i++)
			if (Boolean.TRUE == ScheduleTable.getValueAt(i, 3)) {
				if (ScheduleTable.getValueAt(i, 1).toString().length() > 0
						&& ScheduleTable.getValueAt(i, 2).toString().length() > 0) {
					Interval iv = new Interval(ScheduleTable.getValueAt(i, 1)
							.toString(), ScheduleTable.getValueAt(i, 2)
							.toString());
					System.out.println(iv);
					dp.setPlan(ScheduleTable.getValueAt(i, 0).toString(), iv);
					returnVal = true;
				}
			}
		System.out.println("finished");
		if (returnVal)
			return dp;
		return null;
	}

	/**
	 * This method initializes Add
	 * 
	 * @return javax.swing.JButton
	 */
	private JButton getAdd() {
		if (Add == null) {
			Add = new JButton();
			Add.setBounds(new Rectangle(315, 130, 90, 25));
			Add.setText("Add");
			Add.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					if (Add.getText().equalsIgnoreCase("Add")) {
						Person p = new Person();
						p.setrFid(rfid);
						p.setName(firstName.getText());
						p.setLastName(lastName.getText());
						p.setSex((Sex) sex.getSelectedItem());
						try {
							if (AgeField.getText().length() > 0)
								p.setAge(Integer.parseInt(AgeField.getText()));
							else {
								writeError("Invalid age");
								return;
							}
						} catch (Exception e1) {
							writeError("Invalid age");
							return;
						}
						if (scheduleCB.isSelected()) {
							DayPlan dp = buildDayPlan();
							p.setPlan(dp);
						}
						boolean succes = PersonAchive.add(p);
						if (succes) {
							getDialog().setEnabled(true);
							AddMemberDialog.setVisible(false);
						} else
							writeError("Person Already Exists");
						refreshList();
					} else {
						Person p = new Person();
						p.setName(firstName.getText());
						p.setLastName(lastName.getText());
						p.setSex((Sex) sex.getSelectedItem());
						try {
							if (AgeField.getText().length() > 0)
								p.setAge(Integer.parseInt(AgeField.getText()));
							else {
								writeError("Invalid age");
								return;
							}
						} catch (Exception e1) {
							writeError("Invalid age");
							return;
						}
						if (scheduleCB.isSelected()) {
							DayPlan dp = buildDayPlan();
							p.setPlan(dp);
						}
						PersonAchive.update(selected, p);
						refreshList();
						getDialog().setEnabled(true);
						AddMemberDialog.setVisible(false);

					}

				}
			});
		}
		return Add;
	}

	/**
	 * This method initializes AddMember
	 * 
	 * @return javax.swing.JButton
	 */
	private JButton getAddMember() {
		if (AddMember == null) {
			AddMember = new JButton();
			AddMember.setText("Add Member");
			AddMember.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					AddMemberDialog = getAddMemberDialog();
					firstName.setText("");
					lastName.setText("");
					ScheduleTable = getScheduleTable();
					AgeField.setText("");
					rfLabel.setText("Add RFID");
					rfLabel.setForeground(Constants.red);
					scheduleCB.setSelected(false);
					AddMemberDialog.setSize(440, 277);
					Add.setEnabled(false);
					sex.setSelectedIndex(0);
					AddRFSensor.setEnabled(true);
					Add.setText("Add");
					((PersonTableModel) ScheduleTable.getModel()).clearModel();
					MemberSchedule.setEnabled(false);
					AddMemberDialog.setVisible(true);
					FamilyDialog.this.setEnabled(false);

				}
			});
		}
		return AddMember;
	}

	/**
	 * This method initializes AddMemberDialog
	 * 
	 * @return javax.swing.JDialog
	 */
	JDialog getAddMemberDialog() {
		if (AddMemberDialog == null) {
			AddMemberDialog = new JDialog(this);
			AddMemberDialog.setTitle("Add new Member");
			AddMemberDialog.setBounds(new Rectangle(0, 0, 440, 482));
			AddMemberDialog.setContentPane(getMemberDialogPanel());
			AddMemberDialog
					.addWindowListener(new java.awt.event.WindowAdapter() {
						@Override
						public void windowClosing(java.awt.event.WindowEvent e) {
							FamilyDialog.this.setEnabled(true);
							AddMemberDialog.setVisible(false);
						}
					});
		}
		return AddMemberDialog;
	}

	private JButton getAddRFSensor() {
		if (AddRFSensor == null) {
			AddRFSensor = new JButton();
			AddRFSensor.setText("Add RFID sensor");
			AddRFSensor.setBounds(new Rectangle(200, 195, 150, 25));
			AddRFSensor.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					rfid = new Sensor();
					rfid.setType(SensorType.RF_SENSOR);
					setRF(rfid);
					if (lastName.getText().length() != 0
							&& firstName.getText().length() != 0
							&& AgeField.getText().length() != 0
							&& AddRFSensor.isEnabled() == false) {
						Add.setEnabled(true);

					} else
						Add.setEnabled(false);
				}
			});
		}
		return AddRFSensor;
	}

	/**
	 * This method initializes AgeField
	 * 
	 * @return javax.swing.JTextField
	 */
	private JTextField getAgeField() {
		if (AgeField == null) {
			AgeField = new JTextField();
			AgeField.setBounds(new Rectangle(130, 125, 60, 25));
			AgeField.setHorizontalAlignment(SwingConstants.CENTER);
			AgeField.addKeyListener(new java.awt.event.KeyAdapter() {
				@Override
				public void keyReleased(java.awt.event.KeyEvent e) {
					try {
						Integer.parseInt(AgeField.getText());
						writeError("");
					} catch (Exception e1) {
						writeError("Invalid age");
					}
					if (lastName.getText().length() != 0
							&& firstName.getText().length() != 0
							&& AgeField.getText().length() != 0
							&& AddRFSensor.isEnabled() == false) {
						Add.setEnabled(true);

					} else
						Add.setEnabled(false);
				}
			});
		}
		return AgeField;
	}

	/**
	 * This method initializes Cancel
	 * 
	 * @return javax.swing.JButton
	 */
	private JButton getCancel() {
		if (Cancel == null) {
			Cancel = new JButton();
			Cancel.setBounds(new Rectangle(315, 160, 90, 25));
			Cancel.setText("Cancel");
			Cancel.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					FamilyDialog.this.setEnabled(true);
					AddMemberDialog.setVisible(false);
				}
			});
		}
		return Cancel;
	}

	public FamilyDialog getDialog() {
		return this;
	}

	/**
	 * This method initializes firstName
	 * 
	 * @return javax.swing.JTextField
	 */
	private JTextField getFirstName() {
		if (firstName == null) {
			firstName = new JTextField();
			firstName.setBounds(new Rectangle(130, 30, 180, 25));
			firstName.setHorizontalAlignment(SwingConstants.CENTER);

			firstName.addKeyListener(new java.awt.event.KeyAdapter() {
				@Override
				public void keyTyped(java.awt.event.KeyEvent e) {
					updateName();
					if (lastName.getText().length() != 0
							&& firstName.getText().length() != 0
							&& AgeField.getText().length() != 0
							&& AddRFSensor.isEnabled() == false) {
						Add.setEnabled(true);

					} else
						Add.setEnabled(false);

				}
			});
		}
		return firstName;
	}

	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJContentPane() {
		if (jContentPane == null) {
			jContentPane = new JPanel();
			jContentPane.setLayout(new BorderLayout());
			jContentPane.setBackground(Color.WHITE);
			jContentPane.setBorder(BorderFactory.createCompoundBorder(
					BorderFactory.createBevelBorder(BevelBorder.RAISED),
					BorderFactory.createTitledBorder(BorderFactory
							.createLineBorder(Color.gray, 5), "Family Members",
							TitledBorder.DEFAULT_JUSTIFICATION,
							TitledBorder.DEFAULT_POSITION, new Font(
									"SansSerif", Font.BOLD, 14),
							SystemColor.textHighlight)));
			jContentPane.add(getAddMember(), BorderLayout.SOUTH);
			jContentPane.add(getMemberList(), BorderLayout.CENTER);
		}
		return jContentPane;
	}

	/**
	 * This method initializes lastName
	 * 
	 * @return javax.swing.JTextField
	 */
	private JTextField getLastName() {
		if (lastName == null) {
			lastName = new JTextField();
			lastName.setBounds(new Rectangle(130, 60, 180, 25));
			lastName.setHorizontalAlignment(SwingConstants.CENTER);
			lastName.addKeyListener(new java.awt.event.KeyAdapter() {
				@Override
				public void keyTyped(java.awt.event.KeyEvent e) {
					updateName();
					if (lastName.getText().length() != 0
							&& firstName.getText().length() != 0
							&& AgeField.getText().length() != 0
							&& AddRFSensor.isEnabled() == false) {
						Add.setEnabled(true);

					} else
						Add.setEnabled(false);

				}
			});
		}
		return lastName;
	}

	/**
	 * This method initializes memberDialogPanel
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getMemberDialogPanel() {
		if (memberDialogPanel == null) {
			memberDialogPanel = new JPanel();
			memberDialogPanel.setLayout(null);
			memberDialogPanel.setBackground(Color.white);
			memberDialogPanel.add(getMemberInfo(), null);
			memberDialogPanel.add(getMemberSchedule(), null);
			FormatInfo = new JLabel();
			FormatInfo.setBounds(new Rectangle(1, 237, 420, 25));
			FormatInfo.setFont(new Font("SansSerif", Font.BOLD | Font.ITALIC,
					14));
			FormatInfo.setHorizontalAlignment(SwingConstants.CENTER);
			FormatInfo
					.setToolTipText("Enter Leave-Time and Home-Time in this format");
			FormatInfo.setText("Time Format -  hh:mm");

			memberDialogPanel.add(FormatInfo);
		}
		return memberDialogPanel;
	}

	private JPanel getMemberInfo() {
		if (MemberInfo == null) {
			rfLabel = new JLabel();
			rfLabel.setBounds(new Rectangle(20, 195, 170, 25));
			rfLabel.setHorizontalAlignment(SwingConstants.CENTER);
			rfLabel.setText("");
			aLabel = new JLabel();
			aLabel.setBounds(new Rectangle(20, 125, 90, 25));
			aLabel.setHorizontalTextPosition(SwingConstants.RIGHT);
			aLabel.setHorizontalAlignment(SwingConstants.RIGHT);
			aLabel.setText("Age:");
			ErrorLabel = new JLabel();
			ErrorLabel.setBounds(new Rectangle(160, 160, 150, 25));
			ErrorLabel.setText("");
			ErrorLabel.setForeground(new Color(196, 0, 0));
			ErrorLabel.setHorizontalAlignment(SwingConstants.CENTER);
			Schedule = new JLabel();
			Schedule.setBounds(new Rectangle(20, 160, 90, 25));
			Schedule.setHorizontalTextPosition(SwingConstants.RIGHT);
			Schedule.setHorizontalAlignment(SwingConstants.RIGHT);
			Schedule.setText("Schedule");
			sLabel = new JLabel();
			sLabel.setBounds(new Rectangle(20, 90, 90, 25));
			sLabel.setHorizontalTextPosition(SwingConstants.RIGHT);
			sLabel.setHorizontalAlignment(SwingConstants.RIGHT);
			sLabel.setText("Sex:");
			lnLabel = new JLabel();
			lnLabel.setBounds(new Rectangle(20, 60, 90, 25));
			lnLabel.setHorizontalTextPosition(SwingConstants.RIGHT);
			lnLabel.setHorizontalAlignment(SwingConstants.RIGHT);
			lnLabel.setText("Last Name:");
			fnLabel = new JLabel();
			fnLabel.setBounds(new Rectangle(20, 30, 90, 25));
			fnLabel.setHorizontalTextPosition(SwingConstants.RIGHT);
			fnLabel.setHorizontalAlignment(SwingConstants.RIGHT);
			fnLabel.setText("First Name:");
			MemberInfo = new JPanel();
			MemberInfo.setLayout(null);
			MemberInfo.setBorder(BorderFactory.createCompoundBorder(
					BorderFactory.createBevelBorder(BevelBorder.RAISED),
					BorderFactory.createTitledBorder(BorderFactory
							.createLineBorder(Color.gray, 5), "Information",
							TitledBorder.DEFAULT_JUSTIFICATION,
							TitledBorder.DEFAULT_POSITION, new Font(
									"SansSerif", Font.BOLD, 14),
							SystemColor.textHighlight)));
			MemberInfo.setBackground(new Color(250, 250, 250));
			MemberInfo.setBounds(new Rectangle(0, 0, 425, 240));
			MemberInfo.add(fnLabel, null);
			MemberInfo.add(lnLabel, null);
			MemberInfo.add(getFirstName(), null);
			MemberInfo.add(getLastName(), null);
			MemberInfo.add(sLabel, null);
			MemberInfo.add(getSex(), null);
			MemberInfo.add(Schedule, null);
			MemberInfo.add(getScheduleCB(), null);
			MemberInfo.add(getAdd(), null);
			MemberInfo.add(getCancel(), null);

			MemberInfo.add(ErrorLabel, null);
			MemberInfo.add(aLabel, null);
			MemberInfo.add(getAgeField(), null);
			MemberInfo.add(rfLabel, null);
			MemberInfo.add(getAddRFSensor(), null);
		}
		return MemberInfo;
	}

	/**
	 * This method initializes MemberList
	 * 
	 * @return javax.swing.JList
	 */
	private JList getMemberList() {
		if (MemberList == null) {
			MemberList = new JList();
			MemberList.setFixedCellHeight(16);
			MemberList.setToolTipText("Right-Click to remove or edit a person");
			MemberList.addMouseListener(new java.awt.event.MouseAdapter() {
				@Override
				public void mousePressed(java.awt.event.MouseEvent e) {
					if (e.getButton() > 1 && !MemberList.isSelectionEmpty()) {
						selected = MemberList.getSelectedIndex();
						PersonListPopupMenu PLPM = new PersonListPopupMenu(
								PersonAchive.getPerson(MemberList
										.getSelectedIndex()));
						PLPM.getRoomPopUp(getDialog()).show(MemberList,
								e.getX(), e.getY());
					}
				}
			});
		}
		return MemberList;
	}

	/**
	 * This method initializes MemberSchedule
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getMemberSchedule() {
		if (MemberSchedule == null) {
			MemberSchedule = new JPanel();

			MemberSchedule.setBorder(BorderFactory.createCompoundBorder(
					BorderFactory.createBevelBorder(BevelBorder.RAISED),
					BorderFactory.createTitledBorder(BorderFactory
							.createLineBorder(Color.gray, 5), "Daily Schedule",
							TitledBorder.DEFAULT_JUSTIFICATION,
							TitledBorder.DEFAULT_POSITION, new Font(
									"SansSerif", Font.BOLD, 14),
							SystemColor.textHighlight)));

			MemberSchedule.setBackground(Color.white);
			MemberSchedule.setBounds(new Rectangle(0, 260, 425, 186));
			MemberSchedule.setLayout(new BorderLayout());
			MemberSchedule.add(getTableScrollPanel(), BorderLayout.CENTER);

		}
		return MemberSchedule;
	}

	/**
	 * This method initializes scheduleCB
	 * 
	 * @return javax.swing.JCheckBox
	 */
	private JCheckBox getScheduleCB() {
		if (scheduleCB == null) {
			scheduleCB = new JCheckBox();
			scheduleCB.setBounds(new Rectangle(130, 160, 25, 25));
			scheduleCB.setToolTipText("Mark this to fill out schedule");
			scheduleCB.setBackground(Color.white);

			scheduleCB.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					if (scheduleCB.isSelected()) {
						AddMemberDialog.setSize(440, 482);
						MemberSchedule.setEnabled(true);
					} else {
						AddMemberDialog.setSize(440, 277);
						MemberSchedule.setEnabled(false);

					}
				}
			});
		}
		return scheduleCB;
	}

	private JTable getScheduleTable() {
		if (ScheduleTable == null) {
			PersonTableModel ptm = new PersonTableModel();
			ScheduleTable = new JTable(ptm);
			ScheduleTable.setBounds(new Rectangle(25, 25, 370, 130));
			ScheduleTable.setRowHeight(18);
			DefaultTableCellRenderer dtcr = new DefaultTableCellRenderer();
			dtcr.setHorizontalAlignment(SwingConstants.CENTER);
			ScheduleTable.getColumn("Home-Time").setCellRenderer(dtcr);
			ScheduleTable.getColumn("Leave-Time").setCellRenderer(dtcr);
			ScheduleTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
			ScheduleTable.setFont(new Font("Dialog", Font.BOLD, 12));
			ScheduleTable.setCellSelectionEnabled(true);

		}
		return ScheduleTable;
	}

	/**
	 * This method initializes sex
	 * 
	 * @return javax.swing.JComboBox
	 */
	private JComboBox getSex() {
		if (sex == null) {
			sex = new JComboBox(Sex.toList());
			sex.setBackground(new Color(250, 250, 250));
			sex.setBounds(new Rectangle(130, 90, 120, 25));
		}
		return sex;
	}

	/**
	 * This method initializes ScheduleTable
	 * 
	 * @return javax.swing.JTable
	 */

	private JScrollPane getTableScrollPanel() {
		if (TableScrollPanel == null) {
			TableScrollPanel = new JScrollPane();
			TableScrollPanel.setViewportView(getScheduleTable());
		}
		return TableScrollPanel;
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		this.setSize(232, 307);
		this.setTitle("Family Dialog");
		this.setContentPane(getJContentPane());
		refreshList();

		this.addWindowListener(new java.awt.event.WindowAdapter() {
			@Override
			public void windowClosing(java.awt.event.WindowEvent e) {
				MainGUI.getInstance().setEnabled(true);
				FamilyDialog.this.setVisible(false);

			}
		});
	}

	public void refreshList() {
		for (int i = 0; i < PersonAchive.getCount(); i++) {
			MemberList.setListData(PersonAchive.getList());
		}
	}

	public void setData(Person p) {
		System.out.println(p.getName());
		firstName.setText(p.getName());
		lastName.setText(p.getLastName());
		AgeField.setText(p.getAge() + "");
		sex.setSelectedItem(p.getSex());
		setRF(p.getrFid());
	}

	private void setRF(Sensor sensor) {
		if (sensor != null) {
			AddRFSensor.setEnabled(false);
			rfLabel.setText("RFID = " + sensor.getSensorName());
			rfLabel.setForeground(Constants.green);
		} else {
			rfLabel.setText("Add RFID");
			rfLabel.setForeground(Constants.red);
			Add.setEnabled(false);
		}
	}

	public void updateName() {
		if (lastName.getText().length() > 0) {
			String aux = lastName.getText();
			aux = aux.substring(0, 1).toUpperCase() + aux.substring(1);
			lastName.setText(aux);
		}
		if (firstName.getText().length() > 0) {
			String aux = firstName.getText();
			aux = aux.substring(0, 1).toUpperCase() + aux.substring(1);
			firstName.setText(aux);
		}

	}

	/**
	 * This method initializes MemberInfo
	 * 
	 * @return javax.swing.JPanel
	 */
	private void writeError(String s) {
		if (s.length() == 0) {
			Add.setEnabled(true);
			ErrorLabel.setText("");
		} else {
			Add.setEnabled(false);
			ErrorLabel.setText(s);
		}
	}

} // @jve:decl-index=0:visual-constraint="10,10"
